package com.ruicar.afs.cloud.apply.pre.smallprogram.service.impl;



import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.ApplySignRelationService;
import com.ruicar.afs.cloud.apply.business.service.ApplySmsSendService;
import com.ruicar.afs.cloud.apply.common.condition.SendMessageCondition;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCustBaseInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplySignRelation;
import com.ruicar.afs.cloud.apply.common.entity.PreApproveInfo;
import com.ruicar.afs.cloud.apply.common.feign.ApplyContractFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppSignAgreeMentCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCustBaseInfoService;
import com.ruicar.afs.cloud.apply.pre.smallprogram.condition.TencentCloudNuclearBodyCondition;
import com.ruicar.afs.cloud.apply.pre.smallprogram.dto.ChangeBankInfoDTO;
import com.ruicar.afs.cloud.apply.pre.smallprogram.service.ApplySmallProgramService;
import com.ruicar.afs.cloud.bizcommon.face.dto.TencentCloudNuclearBodyDto;
import com.ruicar.afs.cloud.bizcommon.face.service.TencentCloudNuclearBodyService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.tencentcloudapi.faceid.v20180301.models.DetectAuthResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.*;
import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.YES;


/**
 * @ClassName ApplySmallProgramService
 * @Description: 小程序service
 * @Author mingzhi.li
 * @Date 2020/9/24
 * @Version V1.0
 **/
@Slf4j
@Service
@Component
@AllArgsConstructor
public class ApplySmallProgramServiceImpl implements ApplySmallProgramService {

    private final ApplyContractFeign applyContractFeign;
    private final ApplyConfig applyConfig;
    private final ApplySignRelationService applySignRelationService;
    private final PreApproveService preApproveService;
    private final ApplySmsSendService applySmsSendService;
    private final TencentCloudNuclearBodyService tencentCloudNuclearBodyService;
    private final ComAttachmentFileService attachmentFileService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    /**
     * 获取贷后合同信息
     *
     * @param caseNo
     * @return
     */
    @Override
    public ChangeBankInfoDTO getBankCardInfo(String caseNo) {

        ChangeBankInfoDTO dto = new ChangeBankInfoDTO();
        dto.setCaseNo(caseNo);
        IResponse iResponse = applyContractFeign.queryContractBankInfo(dto, this.makeContractHeader());
        if(CODE_SUCCESS.equals(iResponse.getCode())){
            Map map = (Map) iResponse.getData();
            dto.setOldBankAccount((String) map.get("oldBankAccount"));
            dto.setNewBankAccount((String) map.get("newBankAccount"));
            dto.setOldCardholder((String) map.get("oldCardholder"));
            dto.setNewCardholder((String) map.get("newCardholder"));
            dto.setProvince((String) map.get("province"));
            dto.setCity((String) map.get("city"));
            dto.setOldProvince((String) map.get("oldProvince"));
            dto.setOldCity((String) map.get("oldCity"));
            dto.setNewBank((String) map.get("newBank"));
            dto.setOldBank((String) map.get("oldBank"));
            dto.setContractNo((String) map.get("contractNo"));
            dto.setCertNo((String) map.get("certNo"));
            dto.setPhone((String) map.get("contactNo"));
            dto.setCustName((String) map.get("custName"));
            dto.setKeyWord((String) map.get("keyWord"));
        }
        return dto;
    }

    /**
     * 获取合同系统请求头
     *
     * @return
     */
    public Map makeContractHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("clientId", applyConfig.getContractClientId());
        headers.put("clientSecret", applyConfig.getContractClientSecret());
        return headers;
    }

    /**
     * 获取签约变更银行卡签约文件
     * @param caseNo
     * @return
     */
    @Override
    public List<ComAttachmentFile> getFileList(String caseNo) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        ChangeBankInfoDTO dto = new ChangeBankInfoDTO();
        dto.setCaseNo(caseNo);
        IResponse iResponse = applyContractFeign.getBankCardPermit(dto, this.makeContractHeader());
        if(CODE_SUCCESS.equals(iResponse.getCode())){
            Map map = (Map) iResponse.getData();
            ComAttachmentFile file = new ComAttachmentFile();
            file.setId(Long.valueOf((String) map.get("id")));
            file.setBusiNo((String) map.get("busiNo"));
            file.setBelongNo((String) map.get("belongNo"));
            file.setAttachmentCode((String) map.get("attachmentCode"));
            file.setAttachmentName((String) map.get("attachmentName"));
            file.setFileStatus((String) map.get("fileStatus"));
            file.setFileType((String) map.get("fileType"));
            file.setHistoryVersion((String) map.get("historyVersion"));
            file.setIsElectronic((String) map.get("isElectronic"));
            file.setElectronicNo((String) map.get("electronicNo"));
            file.setFileName((String) map.get("fileName"));
            file.setFileId((String) map.get("fileId"));
            file.setDelFlag((String) map.get("delFlag"));
            file.setArchiveClass((String) map.get("archiveClass"));
            file.setFileSource((String) map.get("fileSource"));
            fileList.add(file);
        }
        return fileList;
    }

    /**
     * 回传签约文件信息到合同系统
     * @param file
     * @return
     */
    @Override
    public IResponse sendFileList(ComAttachmentFile file) {
        applyContractFeign.sendBankCardPermit(file, this.makeContractHeader());
        return IResponse.success("发送成功");
    }

    /**
     * 小程序：预审批场景
     * @param condition
     * @return
     */
    @Override
    public IResponse signScenePre(TencentCloudNuclearBodyCondition condition) {

        if(condition.getPreId()==null){
            return IResponse.fail("预审客户id不能为空！");
        }
        log.info("获取客户预审批信息");
        PreApproveInfo info = preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                .eq(PreApproveInfo::getId, condition.getPreId().toString()));
        if(info ==null){
            return IResponse.fail("客户信息不存在");
        }
        log.info("校验预审批短信验证码开始");
        ApplyAppSignAgreeMentCondition mentCondition = new ApplyAppSignAgreeMentCondition();
        mentCondition.setPreId(info.getId());
        mentCondition.setSignScene(MESSAGE_TYPE_ZERO);
        List<ComAttachmentFile> fileList = getPreFileList(mentCondition);
        if(fileList ==null && fileList.size()==0){
            return IResponse.fail("签约文件不存在");
        }
        SendMessageCondition messageCondition = new SendMessageCondition();
        messageCondition.setMessageType(MESSAGE_TYPE_ONE);
        messageCondition.setUsageScenarios(USAGESCENARIOS_TYPE_ZERO);
        messageCondition.setCertNo(info.getCertNo());
        messageCondition.setRandomCode(condition.getVerCode());
        messageCondition.setBusinessType(info.getBusinessType());
        messageCondition.setPreId(condition.getPreId());
        IResponse verCodeFlag = applySmsSendService.check(messageCondition);
        if(!Boolean.TRUE.equals(verCodeFlag.getData())){
            return IResponse.fail("验证码错误");
        }
        info.setThreeCaResult(YES);
        log.info("请求腾讯云接口开始");
        TencentCloudNuclearBodyDto dto = new TencentCloudNuclearBodyDto();
        dto.setIdCard(info.getCertNo());
        dto.setName(info.getCustName());
        DetectAuthResponse response = tencentCloudNuclearBodyService.tencentCloudFaceCheck(dto);
        //返回bizToken、文件流数据
        JSONObject json = new JSONObject();
        if(response !=null){
            json.put("bizToken",response.getBizToken());
        }else{
            json.put("bizToken","");
        }
        json.put("file",fileList);
        preApproveService.updateById(info);
        return IResponse.success(json);
    }

    /**
     * 小程序：贷后银行卡变更
     * @param condition
     * @return
     */
    @Override
    public IResponse signSceneChangeBankInfo(TencentCloudNuclearBodyCondition condition) {

        if(StrUtil.isBlank(condition.getCaseNo())){
            return IResponse.fail("贷后银行卡变更编号不能为空！");
        }
        if(condition.getCaseId()==null){
            return IResponse.fail("贷后银行卡变更id不能为空！");
        }
        log.info("校验客户详情短信验证码开始");
        SendMessageCondition messageCondition = new SendMessageCondition();
        messageCondition.setMessageType(MESSAGE_TYPE_THREE);
        messageCondition.setUsageScenarios(USAGESCENARIOS_TYPE_THREE);
        messageCondition.setRandomCode(condition.getVerCode());
        messageCondition.setCaseId(condition.getCaseId());
        IResponse verCodeFlag = applySmsSendService.check(messageCondition);
        if(!Boolean.TRUE.equals(verCodeFlag.getData())){
            return IResponse.fail("验证码错误");
        }
        List<ComAttachmentFile> fileList = this.getFileList(condition.getCaseNo());
        if(fileList ==null && fileList.size()==0){
            return IResponse.fail("签约文件不存在");
        }
        log.info("请求腾讯云接口开始");
        ChangeBankInfoDTO infoDTO =this.getBankCardInfo(condition.getCaseNo());
        TencentCloudNuclearBodyDto dto = new TencentCloudNuclearBodyDto();
        dto.setIdCard(infoDTO.getCertNo());
        dto.setName(infoDTO.getCustName());
        DetectAuthResponse response = tencentCloudNuclearBodyService.tencentCloudFaceCheck(dto);
        log.info("bizToken打印："+response.getBizToken());
        //返回bizToken、文件流数据
        JSONObject json = new JSONObject();
        json.put("bizToken",response.getBizToken());
        json.put("file",fileList);
        return IResponse.success(json);
    }

    /**
     * 小程序：小程序：主借人、共借人、担保人场景
     * @param condition
     * @return
     */
    @Override
    public IResponse signSceneRole(TencentCloudNuclearBodyCondition condition) {

        if(condition.getCustId()==null){
            return IResponse.fail("客户id不能为空！");
        }
        if(StrUtil.isBlank(condition.getApplyNo())){
            return IResponse.fail("申请编号不能为空！");
        }
        log.info("获取客户详情开始");
        ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getId, condition.getCustId()));
        if(custBaseInfo ==null){
            return IResponse.fail("客户信息不存在！");
        }
        ApplyAppSignAgreeMentCondition mentCondition = new ApplyAppSignAgreeMentCondition();
        mentCondition.setCustId(custBaseInfo.getId());
        mentCondition.setApplyNo(custBaseInfo.getApplyNo());
        List<ComAttachmentFile> fileList = getPreFileList(mentCondition);
        if(fileList ==null || fileList.size()==0){
            return IResponse.fail("签约文件不存在");
        }
        log.info("校验客户详情短信验证码开始");
        SendMessageCondition messageCondition = new SendMessageCondition();
        messageCondition.setMessageType(MESSAGE_TYPE_ONE);
        messageCondition.setUsageScenarios(USAGESCENARIOS_TYPE_ONE);
        messageCondition.setCertNo(custBaseInfo.getCertNo());
        messageCondition.setRandomCode(condition.getVerCode());
        messageCondition.setApplyNo(condition.getApplyNo());
        messageCondition.setCustId(condition.getCustId());
        IResponse verCodeFlag = applySmsSendService.check(messageCondition);
        if(!Boolean.TRUE.equals(verCodeFlag.getData())){
            return IResponse.fail("验证码错误");
        }
        log.info("请求腾讯云接口开始");
        TencentCloudNuclearBodyDto dto = new TencentCloudNuclearBodyDto();
        dto.setIdCard(custBaseInfo.getCertNo());
        dto.setName(custBaseInfo.getCustName());
        DetectAuthResponse response = tencentCloudNuclearBodyService.tencentCloudFaceCheck(dto);
        log.info("bizToken打印："+response.getBizToken());
        //返回bizToken、文件流数据
        JSONObject json = new JSONObject();
        json.put("bizToken",response.getBizToken());
        json.put("file",fileList);
        return IResponse.success(json);
    }

    /**
     * 获取角色签约附件
     * @param condition
     * @return
     */
    public List<ComAttachmentFile> getPreFileList(ApplyAppSignAgreeMentCondition condition) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        log.info("从合同签约关系表获取签约数据开始=========》》》》");
        if(MESSAGE_TYPE_ZERO.equals(condition.getSignScene())){
            //预审批获取签约文件
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, condition.getPreId())
                    .eq(ApplySignRelation::getBusinessNo,condition.getPreId().toString()));
            if(signRelationList !=null && signRelationList.size()>0){
                log.info("签约文件list组装开始");
                for(ApplySignRelation relation :signRelationList){
                    List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                            .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                            .eq(ComAttachmentFile::getBusiNo, condition.getPreId().toString()).orderByDesc(ComAttachmentFile::getCreateTime));
                    if(attachmentList !=null && attachmentList.size()>0){
                        attachmentList.get(0).setSignStatus(relation.getStatus());
                        fileList.add(attachmentList.get(0));
                    }
                }
            }
        }else{
            //主借人、共借人、担保人获取签约文件（小程序签约征信授权书）
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, condition.getCustId())
                    .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
            if(signRelationList !=null && signRelationList.size()>0){
                log.info("签约文件list组装开始");
                for(ApplySignRelation relation :signRelationList){
                    List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                            .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                            .eq(ComAttachmentFile::getBusiNo, condition.getApplyNo()).orderByDesc(ComAttachmentFile::getCreateTime));
                    if(attachmentList !=null && attachmentList.size()>0){
                        attachmentList.get(0).setSignStatus(relation.getStatus());
                        fileList.add(attachmentList.get(0));
                    }
                }
            }
        }
        return fileList;
    }
}
